Loading

AI Blitz XIII

Age prediction - classic classification baseline solution

Data preprocessing with augmentations and fine-tuning DenseNet for classification problems.

trancongthinh

Data preprocessing with augmentations and fine-tuning DenseNet for classification problems.

Download AIcrowd CLI

In [2]:
!pip install aicrowd-cli
%load_ext aicrowd.magic
Looking in indexes: https://pypi.org/simple, https://us-python.pkg.dev/colab-wheels/public/simple/
Requirement already satisfied: aicrowd-cli in /usr/local/lib/python3.10/dist-packages (0.1.15)
Requirement already satisfied: click<8,>=7.1.2 in /usr/local/lib/python3.10/dist-packages (from aicrowd-cli) (7.1.2)
Requirement already satisfied: GitPython==3.1.18 in /usr/local/lib/python3.10/dist-packages (from aicrowd-cli) (3.1.18)
Requirement already satisfied: requests<3,>=2.25.1 in /usr/local/lib/python3.10/dist-packages (from aicrowd-cli) (2.27.1)
Requirement already satisfied: requests-toolbelt<1,>=0.9.1 in /usr/local/lib/python3.10/dist-packages (from aicrowd-cli) (0.10.1)
Requirement already satisfied: rich<11,>=10.0.0 in /usr/local/lib/python3.10/dist-packages (from aicrowd-cli) (10.16.2)
Requirement already satisfied: toml<1,>=0.10.2 in /usr/local/lib/python3.10/dist-packages (from aicrowd-cli) (0.10.2)
Requirement already satisfied: tqdm<5,>=4.56.0 in /usr/local/lib/python3.10/dist-packages (from aicrowd-cli) (4.65.0)
Requirement already satisfied: pyzmq==22.1.0 in /usr/local/lib/python3.10/dist-packages (from aicrowd-cli) (22.1.0)
Requirement already satisfied: python-slugify<6,>=5.0.0 in /usr/local/lib/python3.10/dist-packages (from aicrowd-cli) (5.0.2)
Requirement already satisfied: semver<3,>=2.13.0 in /usr/local/lib/python3.10/dist-packages (from aicrowd-cli) (2.13.0)
Requirement already satisfied: gitdb<5,>=4.0.1 in /usr/local/lib/python3.10/dist-packages (from GitPython==3.1.18->aicrowd-cli) (4.0.10)
Requirement already satisfied: text-unidecode>=1.3 in /usr/local/lib/python3.10/dist-packages (from python-slugify<6,>=5.0.0->aicrowd-cli) (1.3)
Requirement already satisfied: urllib3<1.27,>=1.21.1 in /usr/local/lib/python3.10/dist-packages (from requests<3,>=2.25.1->aicrowd-cli) (1.26.15)
Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.10/dist-packages (from requests<3,>=2.25.1->aicrowd-cli) (2022.12.7)
Requirement already satisfied: charset-normalizer~=2.0.0 in /usr/local/lib/python3.10/dist-packages (from requests<3,>=2.25.1->aicrowd-cli) (2.0.12)
Requirement already satisfied: idna<4,>=2.5 in /usr/local/lib/python3.10/dist-packages (from requests<3,>=2.25.1->aicrowd-cli) (3.4)
Requirement already satisfied: colorama<0.5.0,>=0.4.0 in /usr/local/lib/python3.10/dist-packages (from rich<11,>=10.0.0->aicrowd-cli) (0.4.6)
Requirement already satisfied: commonmark<0.10.0,>=0.9.0 in /usr/local/lib/python3.10/dist-packages (from rich<11,>=10.0.0->aicrowd-cli) (0.9.1)
Requirement already satisfied: pygments<3.0.0,>=2.6.0 in /usr/local/lib/python3.10/dist-packages (from rich<11,>=10.0.0->aicrowd-cli) (2.14.0)
Requirement already satisfied: smmap<6,>=3.0.1 in /usr/local/lib/python3.10/dist-packages (from gitdb<5,>=4.0.1->GitPython==3.1.18->aicrowd-cli) (5.0.0)

Login to AIcrowd

In [3]:
%aicrowd login
Please login here: https://api.aicrowd.com/auth/iyRAA2JdPVoJiZAanfUQwhWLcZFoSAVc18zR8cOgsPQ
API Key valid
Gitlab access token valid
Saved details successfully!

Download dataset

In [4]:
import os
os.getcwd()
Out[4]:
'/content'
In [5]:
!mkdir data
%aicrowd ds dl -c age-prediction -o data
mkdir: cannot create directory β€˜data’: File exists
ERROR:root:Error while reading the git config, 'NoneType' object has no attribute 'config_reader'
In [6]:
!unzip data/train.zip -d data/train > /dev/null
!unzip data/val.zip -d data/val > /dev/null
!unzip data/test.zip -d data/test > /dev/null

Import the libraries

In [7]:
from sklearn.model_selection import train_test_split
import pandas as pd
import cv2
from matplotlib import pyplot as plt
import numpy as np
import PIL
from PIL import ImageFont, ImageDraw, Image
import time
import tensorflow as tf
from tensorflow.keras.layers import *
from tensorflow.keras.models import Model
from tensorflow.keras.optimizers import Adam

Explore the data

Read the data

In [8]:
train_csv = pd.read_csv(r'/content/data/train.csv')
print("Numer of training input data", len(train_csv))
val_csv = pd.read_csv(r'/content/data/val.csv')
print("Numer of validating input data", len(val_csv))
test_csv = pd.read_csv(r'/content/data/test.csv')
print("Numer of testing input data", len(test_csv))
Numer of training input data 4000
Numer of validating input data 2000
Numer of testing input data 3000
In [9]:
# A very basic method to create complete image paths :)
for i in range(len(train_csv)):
  train_csv.ImageID[i] = train_csv.ImageID[i] + '.jpg'

for i in range(len(val_csv)):
  val_csv.ImageID[i] = val_csv.ImageID[i] + '.jpg'

for i in range(len(test_csv)):
  test_csv.ImageID[i] = test_csv.ImageID[i] + '.jpg'

print(train_csv.head())
     ImageID     age
0  93vu1.jpg   30-40
1  yjifi.jpg   80-90
2  ldd2k.jpg  90-100
3  eiwe0.jpg   40-50
4  sc0bp.jpg    0-10
In [10]:
train_csv.age.unique() # number of classifying classes
Out[10]:
array(['30-40', '80-90', '90-100', '40-50', '0-10', '60-70', '70-80',
       '20-30', '50-60', '10-20'], dtype=object)
In [11]:
def display(im_path):
    dpi = 80
    im_data = plt.imread(im_path)

    height, width  = im_data.shape[:2]

    # What size does the figure need to be in inches to fit the image?
    figsize = width / float(dpi), height / float(dpi)

    # Create a figure of the right size with one axes that takes up the full figure
    fig = plt.figure(figsize=figsize)
    ax = fig.add_axes([0, 0, 1, 1])

    # Hide spines, ticks, etc.
    ax.axis('off')

    # Display the image.
    ax.imshow(im_data, cmap='gray')

    plt.show()
In [12]:
img_path = '/content/data/train/' + train_csv.ImageID[0]
print(img_path)
display(img_path)
/content/data/train/93vu1.jpg
In [13]:
img_path = '/content/data/train/' + train_csv.ImageID[1]
img = cv2.imread(img_path)
print(img.shape) # is it too large for read all image at once?
(512, 512, 3)

Data preparation for training and validating purposes

In [14]:
class_name = ['30-40', '80-90', '90-100', '40-50', '0-10', '60-70', '70-80', '20-30', '50-60', '10-20']
In [15]:
# standardize images
def prep_fn(img):
    img = img.astype(np.float32) / 255.0
    img = (img - 0.5) * 2
    return img

# data generator function for training and validating purposes with simple augmentation
def data_generator(df_train, df_val, train_data_path, val_data_path, img_size, batch_size, seed):
        start_time = time.time()

        training_datagen = tf.keras.preprocessing.image.ImageDataGenerator(
                                preprocessing_function = prep_fn,
                                horizontal_flip = True,
                                vertical_flip = True,
                                brightness_range = [0.8,1.2],
                                fill_mode = 'nearest')
        train_generator = training_datagen.flow_from_dataframe(
                                dataframe = df_train,
                                directory = train_data_path,
                                x_col = "ImageID",
                                y_col = "age",
                                target_size = (img_size, img_size),
                                batch_size = batch_size,
                                class_mode = 'categorical',
                                shuffle = False,
                                seed = seed)

        validation_datagen = tf.keras.preprocessing.image.ImageDataGenerator(
                                preprocessing_function = prep_fn)
        val_generator = validation_datagen.flow_from_dataframe(
                                dataframe = df_val,
                                directory = val_data_path,
                                x_col = "ImageID",
                                y_col = "age",
                                target_size = (img_size, img_size),
                                batch_size = batch_size,
                                class_mode = 'categorical',
                                shuffle = False,
                                seed = seed)

        print(f'----{time.time()-start_time} seconds----')
        return train_generator, val_generator
In [16]:
num_class = 10
img_size = 256
batch_size = 8
seed = 42
lr = 0.02
min_lr = 1e-08
nb_of_epoch = 100
model_name = 'densenet'
In [17]:
train_generator, val_generator = data_generator(df_train = train_csv, df_val = val_csv,
                                                train_data_path = '/content/data/train', val_data_path = '/content/data/val',
                                                img_size = img_size, batch_size = batch_size, seed = seed)

step_per_epoch = train_generator.n//train_generator.batch_size
val_step = val_generator.n//val_generator.batch_size
Found 4000 validated image filenames belonging to 10 classes.
Found 2000 validated image filenames belonging to 10 classes.
----0.07405781745910645 seconds----

Create basic tf.keras.models and training

In [18]:
def scheduler(epoch):
    if epoch<= WARMUP_EPOCH:
        lr = INITIAL_LEARNINGRATE *epoch/WARMUP_EPOCH
    else:
        lr = INITIAL_LEARNINGRATE * DECAY_RATE**(epoch-WARMUP_EPOCH)
    return lr

def get_model(fine_tunning = False, checkpoint_path = 'imagenet'):
    print('--------------Building The Model...--------------')
    base_model = tf.keras.applications.DenseNet121(include_top = False,
                                                   weights = checkpoint_path,
                                                   input_shape = (img_size, img_size, 3))
    base_model.trainable = fine_tunning
    print("\nNumber of layers in the base model: ", len(base_model.layers))
    x = base_model.output
    # x = tf.keras.layers.GlobalMaxPooling2D()(x)
    x = tf.keras.layers.GlobalAveragePooling2D()(x)
    x = tf.keras.layers.Dense(1024,activation='relu')(x)
    x = tf.keras.layers.Dense(512,activation='relu')(x)
    out = tf.keras.layers.Dense(10, activation='softmax')(x)
    model = tf.keras.models.Model(inputs=base_model.input, outputs=out)

    model.compile(loss = 'categorical_crossentropy',
                  optimizer = Adam(learning_rate = lr),
                  metrics='accuracy')

    print('\n--------------Done!--------------')
    return model

model = get_model(fine_tunning = False, checkpoint_path = 'imagenet')
--------------Building The Model...--------------
Downloading data from https://storage.googleapis.com/tensorflow/keras-applications/densenet/densenet121_weights_tf_dim_ordering_tf_kernels_notop.h5
29084464/29084464 [==============================] - 0s 0us/step

Number of layers in the base model:  427

--------------Done!--------------
In [26]:
def train_model(model, lr, model_name,  nb_of_epoch, step_per_epoch, val_step, min_lr, train_generator, val_generator):
    #for layer in base_model.layers[:fine_tune_at]:
    #    layer.trainable =  False
    print('--------------Deploying the Model...--------------')
    monitor = tf.keras.callbacks.EarlyStopping(monitor = 'val_loss',
                                               min_delta = 1e-4,
                                               patience = 5,
                                               verbose = 1,
                                               mode = 'min',
                                               restore_best_weights = True)

    lr_scheduler = tf.keras.callbacks.ReduceLROnPlateau(monitor = "val_loss",
                                                        factor = 0.5,
                                                        patience = 2,
                                                        verbose = 1,
                                                        mode = 'min',
                                                        min_delta = 1e-4,
                                                        cooldown = 0,
                                                        min_lr = min_lr)

    filepath = model_name + "-{epoch:02d}-{val_loss:.4f}.hdf5"

    checkpoint = tf.keras.callbacks.ModelCheckpoint(filepath,
                                                    monitor = 'val_loss',
                                                    verbose = 1,
                                                    save_best_only = False,
                                                    save_weights_only = True,
                                                    mode = 'min',
                                                    save_freq = 'epoch')
    print('--------------Deployed Successfully--------------')
    print('--------------Training Begins--------------')

    history = model.fit(train_generator,
                        epochs = nb_of_epoch,
                        steps_per_epoch = step_per_epoch,
                        validation_data = val_generator,
                        verbose = 1,
                        validation_steps = val_step,
                        callbacks = [monitor, lr_scheduler, checkpoint])
    return history
In [20]:
train_model(model, lr, model_name, nb_of_epoch, step_per_epoch, val_step, min_lr, train_generator, val_generator)
--------------Deploying the Model...--------------
--------------Deployed Successfully--------------
--------------Training Begins--------------
Epoch 1/100
500/500 [==============================] - ETA: 0s - loss: 2.7517 - accuracy: 0.2403
Epoch 1: saving model to densenet-01-1.8212.hdf5
500/500 [==============================] - 73s 113ms/step - loss: 2.7517 - accuracy: 0.2403 - val_loss: 1.8212 - val_accuracy: 0.2920 - lr: 0.0200
Epoch 2/100
500/500 [==============================] - ETA: 0s - loss: 1.7550 - accuracy: 0.3010
Epoch 2: saving model to densenet-02-1.8356.hdf5
500/500 [==============================] - 53s 106ms/step - loss: 1.7550 - accuracy: 0.3010 - val_loss: 1.8356 - val_accuracy: 0.2420 - lr: 0.0200
Epoch 3/100
500/500 [==============================] - ETA: 0s - loss: 1.7074 - accuracy: 0.3090
Epoch 3: saving model to densenet-03-1.7533.hdf5
500/500 [==============================] - 53s 106ms/step - loss: 1.7074 - accuracy: 0.3090 - val_loss: 1.7533 - val_accuracy: 0.2480 - lr: 0.0200
Epoch 4/100
500/500 [==============================] - ETA: 0s - loss: 1.6283 - accuracy: 0.3257
Epoch 4: saving model to densenet-04-1.6207.hdf5
500/500 [==============================] - 53s 106ms/step - loss: 1.6283 - accuracy: 0.3257 - val_loss: 1.6207 - val_accuracy: 0.3425 - lr: 0.0200
Epoch 5/100
500/500 [==============================] - ETA: 0s - loss: 1.6285 - accuracy: 0.3473
Epoch 5: saving model to densenet-05-1.5819.hdf5
500/500 [==============================] - 54s 108ms/step - loss: 1.6285 - accuracy: 0.3473 - val_loss: 1.5819 - val_accuracy: 0.3615 - lr: 0.0200
Epoch 6/100
500/500 [==============================] - ETA: 0s - loss: 1.5971 - accuracy: 0.3532
Epoch 6: saving model to densenet-06-1.5684.hdf5
500/500 [==============================] - 54s 108ms/step - loss: 1.5971 - accuracy: 0.3532 - val_loss: 1.5684 - val_accuracy: 0.3540 - lr: 0.0200
Epoch 7/100
500/500 [==============================] - ETA: 0s - loss: 1.6366 - accuracy: 0.3343
Epoch 7: saving model to densenet-07-1.5579.hdf5
500/500 [==============================] - 60s 120ms/step - loss: 1.6366 - accuracy: 0.3343 - val_loss: 1.5579 - val_accuracy: 0.3590 - lr: 0.0200
Epoch 8/100
500/500 [==============================] - ETA: 0s - loss: 1.6126 - accuracy: 0.3440
Epoch 8: saving model to densenet-08-1.8484.hdf5
500/500 [==============================] - 60s 119ms/step - loss: 1.6126 - accuracy: 0.3440 - val_loss: 1.8484 - val_accuracy: 0.2415 - lr: 0.0200
Epoch 9/100
500/500 [==============================] - ETA: 0s - loss: 1.5480 - accuracy: 0.3548
Epoch 9: ReduceLROnPlateau reducing learning rate to 0.009999999776482582.

Epoch 9: saving model to densenet-09-1.5624.hdf5
500/500 [==============================] - 53s 105ms/step - loss: 1.5480 - accuracy: 0.3548 - val_loss: 1.5624 - val_accuracy: 0.3265 - lr: 0.0200
Epoch 10/100
500/500 [==============================] - ETA: 0s - loss: 1.5232 - accuracy: 0.3692
Epoch 10: saving model to densenet-10-1.4978.hdf5
500/500 [==============================] - 53s 106ms/step - loss: 1.5232 - accuracy: 0.3692 - val_loss: 1.4978 - val_accuracy: 0.3655 - lr: 0.0100
Epoch 11/100
500/500 [==============================] - ETA: 0s - loss: 1.4835 - accuracy: 0.3823
Epoch 11: saving model to densenet-11-1.4982.hdf5
500/500 [==============================] - 53s 105ms/step - loss: 1.4835 - accuracy: 0.3823 - val_loss: 1.4982 - val_accuracy: 0.3715 - lr: 0.0100
Epoch 12/100
500/500 [==============================] - ETA: 0s - loss: 1.4780 - accuracy: 0.3762
Epoch 12: saving model to densenet-12-1.4937.hdf5
500/500 [==============================] - 53s 105ms/step - loss: 1.4780 - accuracy: 0.3762 - val_loss: 1.4937 - val_accuracy: 0.3800 - lr: 0.0100
Epoch 13/100
500/500 [==============================] - ETA: 0s - loss: 1.5108 - accuracy: 0.3735
Epoch 13: saving model to densenet-13-2.3082.hdf5
500/500 [==============================] - 53s 106ms/step - loss: 1.5108 - accuracy: 0.3735 - val_loss: 2.3082 - val_accuracy: 0.2405 - lr: 0.0100
Epoch 14/100
500/500 [==============================] - ETA: 0s - loss: 1.5020 - accuracy: 0.3627
Epoch 14: saving model to densenet-14-1.4895.hdf5
500/500 [==============================] - 53s 106ms/step - loss: 1.5020 - accuracy: 0.3627 - val_loss: 1.4895 - val_accuracy: 0.3480 - lr: 0.0100
Epoch 15/100
500/500 [==============================] - ETA: 0s - loss: 1.4541 - accuracy: 0.3778
Epoch 15: saving model to densenet-15-1.4561.hdf5
500/500 [==============================] - 54s 109ms/step - loss: 1.4541 - accuracy: 0.3778 - val_loss: 1.4561 - val_accuracy: 0.3710 - lr: 0.0100
Epoch 16/100
500/500 [==============================] - ETA: 0s - loss: 1.4982 - accuracy: 0.3593
Epoch 16: saving model to densenet-16-1.6201.hdf5
500/500 [==============================] - 54s 108ms/step - loss: 1.4982 - accuracy: 0.3593 - val_loss: 1.6201 - val_accuracy: 0.3150 - lr: 0.0100
Epoch 17/100
500/500 [==============================] - ETA: 0s - loss: 1.4475 - accuracy: 0.3895
Epoch 17: saving model to densenet-17-1.4531.hdf5
500/500 [==============================] - 55s 110ms/step - loss: 1.4475 - accuracy: 0.3895 - val_loss: 1.4531 - val_accuracy: 0.3840 - lr: 0.0100
Epoch 18/100
500/500 [==============================] - ETA: 0s - loss: 1.4746 - accuracy: 0.3767
Epoch 18: saving model to densenet-18-1.6822.hdf5
500/500 [==============================] - 54s 108ms/step - loss: 1.4746 - accuracy: 0.3767 - val_loss: 1.6822 - val_accuracy: 0.2780 - lr: 0.0100
Epoch 19/100
500/500 [==============================] - ETA: 0s - loss: 1.4519 - accuracy: 0.3850
Epoch 19: ReduceLROnPlateau reducing learning rate to 0.004999999888241291.

Epoch 19: saving model to densenet-19-1.4759.hdf5
500/500 [==============================] - 54s 109ms/step - loss: 1.4519 - accuracy: 0.3850 - val_loss: 1.4759 - val_accuracy: 0.3530 - lr: 0.0100
Epoch 20/100
500/500 [==============================] - ETA: 0s - loss: 1.3941 - accuracy: 0.4027
Epoch 20: saving model to densenet-20-1.4438.hdf5
500/500 [==============================] - 61s 121ms/step - loss: 1.3941 - accuracy: 0.4027 - val_loss: 1.4438 - val_accuracy: 0.3755 - lr: 0.0050
Epoch 21/100
500/500 [==============================] - ETA: 0s - loss: 1.3963 - accuracy: 0.4058
Epoch 21: saving model to densenet-21-1.4495.hdf5
500/500 [==============================] - 54s 108ms/step - loss: 1.3963 - accuracy: 0.4058 - val_loss: 1.4495 - val_accuracy: 0.3745 - lr: 0.0050
Epoch 22/100
500/500 [==============================] - ETA: 0s - loss: 1.3921 - accuracy: 0.4008
Epoch 22: saving model to densenet-22-1.4300.hdf5
500/500 [==============================] - 54s 108ms/step - loss: 1.3921 - accuracy: 0.4008 - val_loss: 1.4300 - val_accuracy: 0.3885 - lr: 0.0050
Epoch 23/100
500/500 [==============================] - ETA: 0s - loss: 1.3930 - accuracy: 0.4042
Epoch 23: saving model to densenet-23-1.4562.hdf5
500/500 [==============================] - 54s 108ms/step - loss: 1.3930 - accuracy: 0.4042 - val_loss: 1.4562 - val_accuracy: 0.3815 - lr: 0.0050
Epoch 24/100
500/500 [==============================] - ETA: 0s - loss: 1.3880 - accuracy: 0.4038
Epoch 24: saving model to densenet-24-1.4121.hdf5
500/500 [==============================] - 55s 110ms/step - loss: 1.3880 - accuracy: 0.4038 - val_loss: 1.4121 - val_accuracy: 0.3900 - lr: 0.0050
Epoch 25/100
500/500 [==============================] - ETA: 0s - loss: 1.4437 - accuracy: 0.3957
Epoch 25: saving model to densenet-25-1.4275.hdf5
500/500 [==============================] - 61s 121ms/step - loss: 1.4437 - accuracy: 0.3957 - val_loss: 1.4275 - val_accuracy: 0.3755 - lr: 0.0050
Epoch 26/100
500/500 [==============================] - ETA: 0s - loss: 1.4115 - accuracy: 0.4008
Epoch 26: saving model to densenet-26-1.4099.hdf5
500/500 [==============================] - 61s 122ms/step - loss: 1.4115 - accuracy: 0.4008 - val_loss: 1.4099 - val_accuracy: 0.3970 - lr: 0.0050
Epoch 27/100
500/500 [==============================] - ETA: 0s - loss: 1.3981 - accuracy: 0.3988
Epoch 27: saving model to densenet-27-1.6543.hdf5
500/500 [==============================] - 54s 108ms/step - loss: 1.3981 - accuracy: 0.3988 - val_loss: 1.6543 - val_accuracy: 0.2835 - lr: 0.0050
Epoch 28/100
500/500 [==============================] - ETA: 0s - loss: 1.4179 - accuracy: 0.3918
Epoch 28: saving model to densenet-28-1.4095.hdf5
500/500 [==============================] - 61s 122ms/step - loss: 1.4179 - accuracy: 0.3918 - val_loss: 1.4095 - val_accuracy: 0.3905 - lr: 0.0050
Epoch 29/100
500/500 [==============================] - ETA: 0s - loss: 1.3805 - accuracy: 0.4110
Epoch 29: saving model to densenet-29-1.4024.hdf5
500/500 [==============================] - 55s 110ms/step - loss: 1.3805 - accuracy: 0.4110 - val_loss: 1.4024 - val_accuracy: 0.4000 - lr: 0.0050
Epoch 30/100
500/500 [==============================] - ETA: 0s - loss: 1.3709 - accuracy: 0.4123
Epoch 30: saving model to densenet-30-1.4107.hdf5
500/500 [==============================] - 54s 108ms/step - loss: 1.3709 - accuracy: 0.4123 - val_loss: 1.4107 - val_accuracy: 0.3985 - lr: 0.0050
Epoch 31/100
500/500 [==============================] - ETA: 0s - loss: 1.3899 - accuracy: 0.3977
Epoch 31: ReduceLROnPlateau reducing learning rate to 0.0024999999441206455.

Epoch 31: saving model to densenet-31-1.4076.hdf5
500/500 [==============================] - 54s 109ms/step - loss: 1.3899 - accuracy: 0.3977 - val_loss: 1.4076 - val_accuracy: 0.3985 - lr: 0.0050
Epoch 32/100
500/500 [==============================] - ETA: 0s - loss: 1.3780 - accuracy: 0.4055
Epoch 32: saving model to densenet-32-1.4007.hdf5
500/500 [==============================] - 54s 109ms/step - loss: 1.3780 - accuracy: 0.4055 - val_loss: 1.4007 - val_accuracy: 0.3910 - lr: 0.0025
Epoch 33/100
500/500 [==============================] - ETA: 0s - loss: 1.3716 - accuracy: 0.4162
Epoch 33: saving model to densenet-33-1.4156.hdf5
500/500 [==============================] - 61s 121ms/step - loss: 1.3716 - accuracy: 0.4162 - val_loss: 1.4156 - val_accuracy: 0.3970 - lr: 0.0025
Epoch 34/100
500/500 [==============================] - ETA: 0s - loss: 1.3627 - accuracy: 0.4115
Epoch 34: saving model to densenet-34-1.3906.hdf5
500/500 [==============================] - 54s 108ms/step - loss: 1.3627 - accuracy: 0.4115 - val_loss: 1.3906 - val_accuracy: 0.3980 - lr: 0.0025
Epoch 35/100
500/500 [==============================] - ETA: 0s - loss: 1.3741 - accuracy: 0.4013
Epoch 35: saving model to densenet-35-1.4301.hdf5
500/500 [==============================] - 54s 109ms/step - loss: 1.3741 - accuracy: 0.4013 - val_loss: 1.4301 - val_accuracy: 0.3955 - lr: 0.0025
Epoch 36/100
500/500 [==============================] - ETA: 0s - loss: 1.3636 - accuracy: 0.4140
Epoch 36: ReduceLROnPlateau reducing learning rate to 0.0012499999720603228.

Epoch 36: saving model to densenet-36-1.4419.hdf5
500/500 [==============================] - 54s 107ms/step - loss: 1.3636 - accuracy: 0.4140 - val_loss: 1.4419 - val_accuracy: 0.3835 - lr: 0.0025
Epoch 37/100
500/500 [==============================] - ETA: 0s - loss: 1.3459 - accuracy: 0.4248Restoring model weights from the end of the best epoch: 34.

Epoch 37: saving model to densenet-37-1.3926.hdf5
500/500 [==============================] - 54s 108ms/step - loss: 1.3459 - accuracy: 0.4248 - val_loss: 1.3926 - val_accuracy: 0.4080 - lr: 0.0012
Epoch 37: early stopping
Out[20]:
<keras.callbacks.History at 0x7fec467b07c0>
In [27]:
model.save_weights('best-before-fine-tunning.hdf5')
In [28]:
model = get_model(fine_tunning = True)
checkpoint_path = 'best-before-fine-tunning.hdf5'
model.load_weights(checkpoint_path)
lr = 0.0002
--------------Building The Model...--------------

Number of layers in the base model:  427

--------------Done!--------------
In [29]:
train_model(model, lr, model_name, nb_of_epoch, step_per_epoch, val_step, min_lr, train_generator, val_generator)
--------------Deploying the Model...--------------
--------------Deployed Successfully--------------
--------------Training Begins--------------
Epoch 1/100
500/500 [==============================] - ETA: 0s - loss: 1.3284 - accuracy: 0.4625
Epoch 1: saving model to densenet-01-1.0638.hdf5
500/500 [==============================] - 168s 199ms/step - loss: 1.3284 - accuracy: 0.4625 - val_loss: 1.0638 - val_accuracy: 0.5550 - lr: 2.0000e-04
Epoch 2/100
500/500 [==============================] - ETA: 0s - loss: 0.9380 - accuracy: 0.5993
Epoch 2: saving model to densenet-02-1.2147.hdf5
500/500 [==============================] - 91s 181ms/step - loss: 0.9380 - accuracy: 0.5993 - val_loss: 1.2147 - val_accuracy: 0.5455 - lr: 2.0000e-04
Epoch 3/100
500/500 [==============================] - ETA: 0s - loss: 0.7907 - accuracy: 0.6705
Epoch 3: saving model to densenet-03-0.8050.hdf5
500/500 [==============================] - 91s 181ms/step - loss: 0.7907 - accuracy: 0.6705 - val_loss: 0.8050 - val_accuracy: 0.6420 - lr: 2.0000e-04
Epoch 4/100
500/500 [==============================] - ETA: 0s - loss: 0.6788 - accuracy: 0.7165
Epoch 4: saving model to densenet-04-1.0831.hdf5
500/500 [==============================] - 91s 181ms/step - loss: 0.6788 - accuracy: 0.7165 - val_loss: 1.0831 - val_accuracy: 0.5850 - lr: 2.0000e-04
Epoch 5/100
500/500 [==============================] - ETA: 0s - loss: 0.5972 - accuracy: 0.7577
Epoch 5: ReduceLROnPlateau reducing learning rate to 9.999999747378752e-05.

Epoch 5: saving model to densenet-05-1.0524.hdf5
500/500 [==============================] - 91s 181ms/step - loss: 0.5972 - accuracy: 0.7577 - val_loss: 1.0524 - val_accuracy: 0.6065 - lr: 2.0000e-04
Epoch 6/100
500/500 [==============================] - ETA: 0s - loss: 0.4046 - accuracy: 0.8410
Epoch 6: saving model to densenet-06-0.6879.hdf5
500/500 [==============================] - 92s 184ms/step - loss: 0.4046 - accuracy: 0.8410 - val_loss: 0.6879 - val_accuracy: 0.7510 - lr: 1.0000e-04
Epoch 7/100
500/500 [==============================] - ETA: 0s - loss: 0.3097 - accuracy: 0.8785
Epoch 7: saving model to densenet-07-0.5940.hdf5
500/500 [==============================] - 91s 182ms/step - loss: 0.3097 - accuracy: 0.8785 - val_loss: 0.5940 - val_accuracy: 0.7785 - lr: 1.0000e-04
Epoch 8/100
500/500 [==============================] - ETA: 0s - loss: 0.2794 - accuracy: 0.8905
Epoch 8: saving model to densenet-08-0.5696.hdf5
500/500 [==============================] - 91s 183ms/step - loss: 0.2794 - accuracy: 0.8905 - val_loss: 0.5696 - val_accuracy: 0.7785 - lr: 1.0000e-04
Epoch 9/100
500/500 [==============================] - ETA: 0s - loss: 0.2479 - accuracy: 0.9055
Epoch 9: saving model to densenet-09-0.5699.hdf5
500/500 [==============================] - 91s 181ms/step - loss: 0.2479 - accuracy: 0.9055 - val_loss: 0.5699 - val_accuracy: 0.7840 - lr: 1.0000e-04
Epoch 10/100
500/500 [==============================] - ETA: 0s - loss: 0.2205 - accuracy: 0.9172
Epoch 10: ReduceLROnPlateau reducing learning rate to 4.999999873689376e-05.

Epoch 10: saving model to densenet-10-0.6093.hdf5
500/500 [==============================] - 97s 195ms/step - loss: 0.2205 - accuracy: 0.9172 - val_loss: 0.6093 - val_accuracy: 0.7760 - lr: 1.0000e-04
Epoch 11/100
500/500 [==============================] - ETA: 0s - loss: 0.1183 - accuracy: 0.9610
Epoch 11: saving model to densenet-11-0.6550.hdf5
500/500 [==============================] - 91s 181ms/step - loss: 0.1183 - accuracy: 0.9610 - val_loss: 0.6550 - val_accuracy: 0.7960 - lr: 5.0000e-05
Epoch 12/100
500/500 [==============================] - ETA: 0s - loss: 0.0795 - accuracy: 0.9750
Epoch 12: ReduceLROnPlateau reducing learning rate to 2.499999936844688e-05.

Epoch 12: saving model to densenet-12-0.6126.hdf5
500/500 [==============================] - 97s 193ms/step - loss: 0.0795 - accuracy: 0.9750 - val_loss: 0.6126 - val_accuracy: 0.8090 - lr: 5.0000e-05
Epoch 13/100
500/500 [==============================] - ETA: 0s - loss: 0.0383 - accuracy: 0.9902Restoring model weights from the end of the best epoch: 8.

Epoch 13: saving model to densenet-13-0.6313.hdf5
500/500 [==============================] - 93s 186ms/step - loss: 0.0383 - accuracy: 0.9902 - val_loss: 0.6313 - val_accuracy: 0.8230 - lr: 2.5000e-05
Epoch 13: early stopping
Out[29]:
<keras.callbacks.History at 0x7feba5656e90>
In [30]:
model.save_weights('best-after-fine-tunning.hdf5')
In [32]:
model = get_model(fine_tunning = True)
checkpoint_path = 'best-after-fine-tunning.hdf5'
model.load_weights(checkpoint_path)
--------------Building The Model...--------------

Number of layers in the base model:  427

--------------Done!--------------

Predict test set and submission

In [33]:
test_datagen = tf.keras.preprocessing.image.ImageDataGenerator(preprocessing_function = prep_fn)

test_generator = test_datagen.flow_from_dataframe(
                                dataframe = test_csv,
                                directory = '/content/data/test',
                                x_col = "ImageID",
                                y_col = None,
                                target_size = (img_size, img_size),
                                batch_size = batch_size,
                                class_mode = None,
                                shuffle = False)

STEP_SIZE_TEST = test_generator.n//test_generator.batch_size
pred = model.predict(test_generator,
                     steps = STEP_SIZE_TEST,
                     verbose = 1)

predicted_class_indices = np.argmax(pred, axis = 1)
Found 3000 validated image filenames.
375/375 [==============================] - 31s 77ms/step
In [34]:
labels = (train_generator.class_indices)
labels = dict((v,k) for k,v in labels.items())
predictions = [labels[k] for k in predicted_class_indices]

filenames = test_generator.filenames
for i in range(len(filenames)):
  filenames[i] = filenames[i][:-4]
results = pd.DataFrame({"ImageID": filenames,
                        "age": predictions})
In [35]:
results.head()
Out[35]:
ImageID age
0 8rti7 90-100
1 575pj 10-20
2 6ma92 0-10
3 jtu3e 30-40
4 svx4s 20-30
In [36]:
!rm -rf assets
!mkdir assets
results.to_csv(os.path.join("assets", "submission.csv"))
In [39]:
%aicrowd notebook submit -c age-prediction -a assets --no-verify
An unexpected error occured!
'name'
To get more information, you can run this command with -v.
To increase level of verbosity, you can go upto -vvvvv

Comments

You must login before you can post a comment.

Execute