{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"# Introduction  \nTo improve classification accuracy of the model on the test dataset, the following are explored:\n* Input image size\n* Pretrained model and number of trainable parameters of final model\n* Data augmentation\n* Regularization techniques\n* Use of learning rate schedule\n","metadata":{}},{"cell_type":"markdown","source":"# Import Libraries","metadata":{}},{"cell_type":"code","source":"# This Python 3 environment comes with many helpful analytics libraries installed on Kaggle\n# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python\nimport os\nimport numpy as np \nimport matplotlib.pyplot as plt\nimport tensorflow as tf\nfrom tensorflow.keras import regularizers      # mitigate overfitting \nfrom kaggle_datasets  import KaggleDatasets    # import kaggle data files\n# Stop training when a monitored metric has stopped improving\nfrom tensorflow.keras.callbacks import EarlyStopping   \nprint(\"Tensorflow version \" + tf.__version__)  # verify tensorflow versionis 2.x","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Detect Hardware","metadata":{}},{"cell_type":"code","source":"# Detect hardware, return appropriate distribution strategy\ntry:\n    # TPU detection. No parameters necessary if TPU_NAME environment variable is set. \n    # On Kaggle this is always the case.\n    tpu = tf.distribute.cluster_resolver.TPUClusterResolver()  \n    print('Running on TPU ', tpu.master())\nexcept ValueError:\n    tpu = None\n\nif tpu:\n    tf.config.experimental_connect_to_cluster(tpu)\n    tf.tpu.experimental.initialize_tpu_system(tpu)\n    strategy = tf.distribute.experimental.TPUStrategy(tpu)\nelse:\n    # default distribution strategy in Tensorflow. Works on CPU and single GPU.\n    strategy = tf.distribute.get_strategy() \n\nprint(\"REPLICAS: \", strategy.num_replicas_in_sync)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Data Directories","metadata":{}},{"cell_type":"code","source":"# Input data files are available in the read-only \"kaggle/input/\" directory\n#   image files are in TFRecords format, each of which contains a sequeence\n#   of records and can only be read sequentially.\n\nTFRec_selected = '512x512'\nfor dirpath, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        if TFRec_selected in dirpath: # \n            print(os.path.join(dirpath, filename))","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved \n# as output when you create a version using \"Save & Run All\" \nfor dirpath, _, filenames in os.walk('/kaggle/working'):\n    for filename in filenames:\n        print(os.path.join(dirpath, filename))     \n        \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of \n# the current session\n!gsutil cp /kaggle/input/tpu-getting-started/sample_submission.csv /kaggle/temp/temp1.csv\nfor dirpath, _, filenames in os.walk('/kaggle/temp'):\n    for filename in filenames:\n        print(os.path.join(dirpath, filename))     \n        ","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Set up data path","metadata":{}},{"cell_type":"code","source":"GCS_DS_PATH = KaggleDatasets().get_gcs_path() \n# you can list the bucket with \"!gsutil ls $GCS_DS_PATH\"\nprint(GCS_DS_PATH)\n!gsutil ls $GCS_DS_PATH","metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Set up parameters","metadata":{}},{"cell_type":"code","source":"# parameters set for tfrecords-jpeg-512x512 TFRecord files\nIMAGE_SIZE        = [512, 512] \nHEIGHT            = IMAGE_SIZE[0]\nWIDTH             = IMAGE_SIZE[1]\nEPOCHS            = 20\nBATCH_SIZE        = 16 * strategy.num_replicas_in_sync\nNUM_TRAIN_IMAGES  = 12753\nNUM_VAL_IMAGES    = 3712\nNUM_TEST_IMAGES   = 7382\nSTEPS_PER_EPOCH   = NUM_TRAIN_IMAGES // BATCH_SIZE\nAUTO              = tf.data.experimental.AUTOTUNE\nTRAIN_FILENAMES   = tf.io.gfile.glob(GCS_DS_PATH + '/tfrecords-jpeg-512x512/train/*.tfrec') \nVAL_FILENAMES     = tf.io.gfile.glob(GCS_DS_PATH + '/tfrecords-jpeg-512x512/val/*.tfrec') \nTEST_FILENAMES    = tf.io.gfile.glob(GCS_DS_PATH + '/tfrecords-jpeg-512x512/test/*.tfrec') ","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Functions to handle data","metadata":{}},{"cell_type":"code","source":"def decode_image(image_data):\n    image = tf.image.decode_jpeg(image_data, channels=3)\n    image = tf.cast(image, tf.float32) / 255.0  # convert image to floats in [0, 1] range\n    image = tf.reshape(image, [*IMAGE_SIZE, 3]) # explicit size needed for TPU\n    return image\n\ndef read_labeled_tfrecord(example):\n    LABELED_TFREC_FORMAT = {\n        \"image\": tf.io.FixedLenFeature([], tf.string), # tf.string means bytestring\n        \"class\": tf.io.FixedLenFeature([], tf.int64),  # shape [] means single element\n    }\n    example = tf.io.parse_single_example(example, LABELED_TFREC_FORMAT)\n    image = decode_image(example['image'])\n    label = tf.cast(example['class'], tf.int32)\n    return image, label # returns a dataset of (image, label) pairs\n\ndef read_unlabeled_tfrecord(example):\n    UNLABELED_TFREC_FORMAT = {\n        \"image\": tf.io.FixedLenFeature([], tf.string), # tf.string means bytestring\n        \"id\": tf.io.FixedLenFeature([], tf.string),    # shape [] means single element\n        # class is missing, to be predicted flower classes for the test dataset\n    }\n    example = tf.io.parse_single_example(example, UNLABELED_TFREC_FORMAT)\n    image = decode_image(example['image'])\n    idnum = example['id']\n    return image, idnum # returns a dataset of (image, idnum) pairs\n\ndef load_dataset(filenames, labeled=True, ordered=False):\n    # Read from TFRecords. For optimal performance, reading from multiple files at once and\n    # disregarding data order. Order does not matter since we will be shuffling the data anyway.\n    ignore_order = tf.data.Options()\n    if not ordered:\n        ignore_order.experimental_deterministic = False # disable order, increase speed\n    \n    # automatically interleaves reads from multiple file\n    dataset = tf.data.TFRecordDataset(filenames, num_parallel_reads=AUTO) \n    \n    # uses data as soon as it streams in, rather than in its original order\n    dataset = dataset.with_options(ignore_order) \n    \n    # returns a dataset of (image, label) pairs if labeled=True or (image, id) pairs if labeled=False\n    dataset = dataset.map(read_labeled_tfrecord if labeled \n                          else read_unlabeled_tfrecord, num_parallel_calls=AUTO)\n    return dataset\n\ndef get_validation_dataset(filenames):\n    dataset = load_dataset(filenames,labeled=True, ordered=False)\n    dataset = dataset.cache()\n    dataset = dataset.shuffle(buffer_size=2048)\n    dataset = dataset.batch(BATCH_SIZE)\n    # prefetch next batch while training (autotune prefetch buffer size)\n    dataset = dataset.prefetch(AUTO) \n    return dataset\n\ndef get_test_dataset(filenames, ordered=False):  # order matters to submit predictions to Kaggle\n    dataset = load_dataset(filenames, labeled=False, ordered=ordered)\n    dataset = dataset.batch(BATCH_SIZE)\n    # prefetch next batch while training (autotune prefetch buffer size)\n    dataset = dataset.prefetch(AUTO) \n    return dataset","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Functions to get training dataset with data augmentation option","metadata":{}},{"cell_type":"code","source":"# image augmentation                                  \ndef data_augment(image, label):\n    # Pad the image with a black, 3-pixel border\n    # image = tf.image.resize_with_crop_or_pad(image, HEIGHT + 6, WIDTH + 6)\n    # Randomly crop to original size from the padded image\n    # image = tf.image.random_crop(image, size=[*IMAGE_SIZE,3])\n    image = tf.image.random_flip_left_right(image)\n    image = tf.image.random_contrast(image, 0.8, 1.2)\n    image = tf.image.random_brightness(image, 0.1) \n    image = tf.image.random_saturation(image, 0.7, 1.3)\n    return image, label \n\n# get training datatset with augmentation option\ndef get_training_dataset(filenames, augmentation=False):\n    # Thanks to the dataset.prefetch(AUTO) statement below, data pipeline code \n    #  is executed on the \"CPU\" part of the TPU while the TPU itself is computing gradients.\n    dataset = load_dataset(filenames, labeled=True, ordered=False)\n    if augmentation:\n        dataset = dataset.map(data_augment, num_parallel_calls=AUTO)\n    dataset = dataset.repeat() # the training dataset must repeat for several epochs\n    dataset = dataset.shuffle(buffer_size=2048)\n    dataset = dataset.batch(BATCH_SIZE)\n    dataset = dataset.prefetch(AUTO)  # prefetch next batch while training\n    return dataset","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Functions to visualize images in batches","metadata":{}},{"cell_type":"code","source":"np.set_printoptions(threshold=15, linewidth=80)\n\ndef batch_to_numpy_images_and_labels(data):\n    images, labels = data\n    numpy_images = images.numpy()\n    numpy_labels = labels.numpy()\n    if numpy_labels.dtype == object: # binary string in this case, these are image ID strings\n        numpy_labels = [None for _ in enumerate(numpy_images)]\n    # If no labels, only image IDs, return None for labels (this is the case for test data)\n    return numpy_images, numpy_labels\n\ndef show_images(databatch, row=6, col=8):\n    #row = 6; col = 8;\n    FIGSIZE = col*2\n    plt.figure(figsize=(FIGSIZE,FIGSIZE/col*row))\n    images, num_labl = batch_to_numpy_images_and_labels(databatch)\n    for j in range(row*col):\n        plt.subplot(row,col,j+1)\n        plt.axis('off')\n        plt.title(num_labl[j])\n        plt.imshow(images[j,])\n    plt.show()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Explore image augmentation","metadata":{}},{"cell_type":"code","source":"# get original training_dataset without augmentation\nori_train_set = get_training_dataset(TRAIN_FILENAMES, augmentation=False)\nori_image_batch = (next(iter(ori_train_set.unbatch().batch(16)))) # get a batch for \nimages, _ = batch_to_numpy_images_and_labels(ori_image_batch)\n\n# function to show image with random data augmentation\ndef show_aug(image):\n    plt.figure(figsize=(12,2))\n    plt.subplot(1,6,1)\n    plt.imshow(image)\n    plt.title('no augmentation')\n    plt.axis('off')\n    plt.subplot(1,6,3)\n    plt.imshow(tf.image.random_flip_left_right(image))       # augmented with random flip\n    plt.title('rdm flip L/R')\n    plt.axis('off')    \n    plt.subplot(1,6,4)\n    plt.imshow(tf.image.random_contrast(image, 0.90, 0.99))  # augmented with contrast\n    plt.title('rdm contrast')\n    plt.axis('off')\n    plt.subplot(1,6,5)\n    plt.imshow(tf.image.random_brightness(image, 0.1))       # augmented with brightness\n    plt.title('rdm brightness')\n    plt.axis('off')\n    plt.subplot(1,6,6)\n    plt.imshow(tf.image.random_saturation(image, 0.8, 0.9))  # augmented with saturation\n    plt.title('rdm saturation')\n    plt.axis('off')\n    plt.subplot(1,6,2)\n    image = data_augment(image, None)\n    plt.imshow(image[0])  # any random combinations of the above augmenations, if any\n    plt.title('rdm aug combo')\n    plt.axis('off')    \n    plt.show()\n\n# show images\nprint('Training Dataset')\nprint('Sample Images: Original versus w/ Random Augmentation')\nfor im in images:\n    show_aug(im)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Select train, val and test datasets ","metadata":{}},{"cell_type":"code","source":"# Get training dataset w/o data augmentation to fit model\ntraining_dataset   = get_training_dataset(TRAIN_FILENAMES, augmentation=True)\nvalidation_dataset = get_validation_dataset(VAL_FILENAMES)\n# order of test images matters to submit predictions to Kaggle for a score\ntest_dataset       = get_test_dataset(TEST_FILENAMES, ordered=True)\n\nprint('trainin dataset:    ', training_dataset)\nprint('validation dataset: ', validation_dataset)\nprint('test dataset:       ', test_dataset)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Visualize image samples","metadata":{}},{"cell_type":"code","source":"# you may run these lines repeatedly to take different samples from the image sets\nprint('Training Images with random data augmentation in data pipeline')\nshow_images(next(iter(training_dataset.unbatch().batch(56))), row=7, col=8)\nprint('Validation Images')\nshow_images(next(iter(validation_dataset.unbatch().batch(56))), row=7, col=8)\nprint('Test Images - shuffled')\nshow_images(next(iter(test_dataset.shuffle(buffer_size=80).unbatch().batch(56))), row=7, col=8)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"> # Build the model","metadata":{}},{"cell_type":"code","source":"'''\nAlternatively, data augmentation may be done by creating image preprocessing layers\n   and make them part of the model, as show below:  \n\ndata_augmentation = tf.keras.Sequential([\n   tf.keras.layers.experimental.preprocessing.RandomFlip(\"horizontal_and_vertical\", seed = SEED),\n   tf.keras.layers.experimental.preprocessing.RandomRotation(0.2, seed = SEED)\n])\n'''\n\n# With pretrained model: InceptionV3\nwith strategy.scope():    \n    pretrained_model = tf.keras.applications.DenseNet201(\n        weights='imagenet', \n        include_top=False ,\n        input_shape=[*IMAGE_SIZE, 3]\n    )\n    pretrained_model.trainable = True # transfer learning\n    model = tf.keras.Sequential([\n        pretrained_model,\n        tf.keras.layers.Dropout(0.2),  # moved up\n        tf.keras.layers.GlobalAveragePooling2D(),\n        tf.keras.layers.Dense(104, \n            kernel_regularizer=regularizers.l2(0.00011), \n            activation='softmax')\n    ])\n        \nmodel.compile(\n    optimizer='adam',\n    loss = 'sparse_categorical_crossentropy',\n    metrics=['sparse_categorical_accuracy']\n)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# display pretrained DenseNet201 base model summary\nprint('############ pretrained DenseNet201 base model summary ############')\npretrained_model.summary()","metadata":{"scrolled":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# display model summary\nprint('######################### my model summary ########################')\nmodel.summary()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Monitor model metrics and EarlyStopping","metadata":{}},{"cell_type":"code","source":"# Learning Rate Schedule for Fine Tuning \ndef exponential_lr(epoch,\n                  start_lr=0.00001,min_lr=0.00001,max_lr=0.00005,\n                  rampup_epochs = 5, sustain_epochs = 0,\n                  exp_decay = 0.8):\n    def lr(epoch, start_lr, min_lr,max_lr,rampup_epochs,sustain_epochs,\n          exp_decay):\n        # linear increase from start to rampup_epochs\n        if epoch < rampup_epochs:\n            lr= ((max_lr-start_lr)/\n                rampup_epochs * epoch + start_lr)\n        elif epoch < rampup_epochs + sustain_epochs:\n            lr = max_lr \n        else:\n            lr = ((max_lr - min_lr)* exp_decay ** (epoch-rampup_epochs-sustain_epochs)\n                  + min_lr)\n            \n        return lr\n    return lr(epoch,start_lr,min_lr,max_lr,rampup_epochs,sustain_epochs,exp_decay)\n\nlr_callback = tf.keras.callbacks.LearningRateScheduler(exponential_lr,verbose=True)\n\n# learning rate chart\nepoch_rng = [i for i in range(EPOCHS+31)]\ny = [exponential_lr(x) for x in epoch_rng]\nplt.plot(epoch_rng,y)\nplt.xlim(-1, EPOCHS+32)\n\nprint(\"Learning rate schedule: start = {:.3g}; peak = {:.3g}; end = {:.3g}\".format(y[0], max(y), y[-1]))","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Stop training when a monitored metric has stopped improving\nearlystopping = EarlyStopping(monitor='val_loss', patience=2)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Train the model","metadata":{}},{"cell_type":"code","source":"# fit the model\nhistorical = model.fit(\n    training_dataset, \n    steps_per_epoch=STEPS_PER_EPOCH, \n    epochs=EPOCHS, \n    validation_data=validation_dataset,\n    # continuously monitoring val_loss\n    # adjust learning rate & determine earlystopping\n    callbacks=[lr_callback,earlystopping]  \n)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Plots: accuracy and loss metrics","metadata":{}},{"cell_type":"code","source":"# Create plots of loss and accuracy on the training and validation sets.\n\nacc = historical.history['sparse_categorical_accuracy']\nval_acc = historical.history['val_sparse_categorical_accuracy']\n\nloss = historical.history['loss']\nval_loss = historical.history['val_loss']\n\nepochs_range = range(1, len(historical.history['loss'])+1)\n\nplt.figure(figsize=(14, 14))\nplt.subplot(2, 1, 1)\nplt.plot(epochs_range, acc, label='Training Accuracy')\nplt.plot(epochs_range, val_acc, label='Validation Accuracy')\nplt.legend(loc='lower right')\nplt.title('Training and Validation Accuracy')\nplt.xlabel('Epoch')\n\nplt.subplot(2, 1, 2)\nplt.plot(epochs_range, loss, label='Training Loss')\nplt.plot(epochs_range, val_loss, label='Validation Loss')\nplt.legend(loc='upper right')\nplt.title('Training and Validation Loss')\nplt.xlabel('Epoch')\nplt.show()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Compute predictions on the test set","metadata":{}},{"cell_type":"code","source":"print('Computing predictions...')\ntest_images_ds = test_dataset.map(lambda image, idnum: image)\nprobabilities = model.predict(test_images_ds)\npredictions = np.argmax(probabilities, axis=-1)\nprint(predictions)\n\nprint('Generating submission.csv file...')\ntest_ids_ds = test_dataset.map(lambda image, idnum: idnum).unbatch()\ntest_ids = next(iter(test_ids_ds.batch(NUM_TEST_IMAGES))).numpy().astype('U') # all in one batch\nnp.savetxt('submission.csv', np.rec.fromarrays([test_ids, predictions]), \n           fmt=['%s', '%d'], delimiter=',', header='id,label', comments='')","metadata":{"trusted":true},"execution_count":null,"outputs":[]}]}